#include "daemon_runner.h"
#include "daemon_process.h"
#include "log/log.h"
#include <assert.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>

#define PROCESS_COUNT 2

static DaemonProcess *processes[PROCESS_COUNT];

static int running = 1;

void signal_handler(int sig)
{
    assert(sig == SIGTERM);
    running = 0;
}

void daemon_runner_run(void)
{
    // 将daemon进程转变为后台进程
    daemon(0, 1);
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);
    open("/dev/null", O_RDWR);
    open(LOG_FILE, O_CREAT | O_RDWR, 0644);
    open(LOG_FILE, O_CREAT | O_RDWR, 0644);

    signal(SIGTERM, signal_handler);

    processes[0] = daemon_process_init("app");
    processes[1] = daemon_process_init("ota");
    assert(processes[0]);
    assert(processes[1]);
    while (running)
    {
        for (int i = 0; i < PROCESS_COUNT; i++)
        {
            daemon_process_start(processes[i]);
        }
        sleep(1);
    }

    for (int i = 0; i < PROCESS_COUNT; i++)
    {
        daemon_process_stop(processes[i]);
    }
}